import React from 'react';
import { notification } from 'antd';
import { isPlainObject } from 'lodash';
import {LoadingOutlined} from '@ant-design/icons';
import {childConfig as config} from '@/config';
import { auth } from '@/utils/T';

// const _notification = Object.assign({}, notification);
const prefixCls = `${config.prefixCls}-notification`;

function convertNotificationArgs(args) {
  const config = { prefixCls };
  if (isPlainObject(args)) {
    Object.assign(config, args);
  } else {
    Object.assign(config, { description: args });
  }
  return config;
}

class _notification {
  constructor() {
    notification.config({
      prefixCls,
      top: 84,
      duration: 3,
    });
    this.option = {
      maxCount: 2,
    };
    this.tipDom = document.querySelector(`.${prefixCls}`);
  }

  /**
   * 控制显示个数
   */
  update() {
    if (!auth.getToken()) {
      notification.destroy();
      return false;
    }
    if (!this.tipDom) this.tipDom = document.querySelector(`.${prefixCls}`);
    if (this.tipDom) {
      try {
        const spanDom = this.tipDom.firstChild;
        const childNodes = spanDom.childNodes;
        if (childNodes.length > this.option.maxCount) {
          for (let i = 0; i < childNodes.length - this.option.maxCount; i++) {
            // spanDom.removeChild(childNodes[i])
            childNodes[i].style.display = 'none'; // 此种方法降低操作dom造成的性能消耗
          }
        }
      } catch (e) {}
    }
  }

  success(config) {
    notification.success({
      message: '成功',
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  error(config) {
    notification.error({
      message: '错误',
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  info(config) {
    notification.info({
      message: '消息',
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  warning(config) {
    notification.warning({
      message: '警告',
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  warn(config) {
    notification.warning({
      message: '警告',
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  loading(config) {
    notification.open({
      message: '加载中',
      icon: <LoadingOutlined style={{ color: '#7C8995' }} spin />,
      ...convertNotificationArgs(config),
    });
    this.update();
  }

  open(config) {
    notification.open({
      message: '通知',
      ...convertNotificationArgs(config),
    });
    this.update();
  }
}
export default new _notification();
